<?php

namespace app\controller;

use think\Request;
use app\model\User as UserModel;
use app\model\UserDevice;
use app\model\UserLog;
use Exception;

class User
{
    /**
     * 获取用户信息
     */
    public function getInfo(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $user = UserModel::with(['oauths'])->find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            // 获取用户统计信息
            $stats = $user->getStats();

            return success([
                'user' => $user,
                'stats' => $stats,
            ], '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    public function updateInfo(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $data = $request->only(['nickname', 'avatar', 'master_key_hint']);

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            // 更新允许的字段
            $updateData = [];
            foreach (['nickname', 'avatar', 'master_key_hint'] as $field) {
                if (isset($data[$field])) {
                    $updateData[$field] = $data[$field];
                }
            }

            if (!empty($updateData)) {
                $user->save($updateData);
            }

            // 记录日志
            UserLog::record($userId, 'update_profile', '更新个人资料');

            return success($user, '更新成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $oldPassword = $request->param('old_password');
            $newPassword = $request->param('new_password');

            if (empty($oldPassword) || empty($newPassword)) {
                return error('原密码和新密码不能为空');
            }

            if (strlen($newPassword) < 6) {
                return error('新密码长度不能少于6位');
            }

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            // 验证原密码
            if (!$user->checkPassword($oldPassword)) {
                return error('原密码错误');
            }

            // 更新密码
            $user->password = $newPassword;
            $user->save();

            // 记录日志
            UserLog::record($userId, 'change_password', '修改密码');

            return success(null, '密码修改成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 修改加密方式
     */
    public function changeEncryptMethod(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $deviceId = $request->param('device_id');
            $encryptMethod = $request->param('encrypt_method');

            if (empty($deviceId) || empty($encryptMethod)) {
                return error('设备ID和加密方式不能为空');
            }

            // 验证加密方式是否支持
            $allowedMethods = \app\model\SystemConfig::getEncryptMethods();
            if (!in_array($encryptMethod, $allowedMethods)) {
                return error('不支持的加密方式');
            }

            // 更新设备加密方式
            $device = UserDevice::where('user_id', $userId)
                ->where('device_id', $deviceId)
                ->find();

            if (!$device) {
                return error('设备不存在');
            }

            $device->encrypt_method = $encryptMethod;
            $device->save();

            // 记录日志
            UserLog::record($userId, 'update_profile', "修改加密方式为: {$encryptMethod}");

            return success(null, '加密方式修改成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取设备列表
     */
    public function getDevices(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件

            $devices = UserDevice::where('user_id', $userId)
                ->order('last_active', 'desc')
                ->select();

            return success($devices, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 删除设备
     */
    public function deleteDevice(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $deviceId = $request->param('device_id');

            if (empty($deviceId)) {
                return error('设备ID不能为空');
            }

            $device = UserDevice::where('user_id', $userId)
                ->where('device_id', $deviceId)
                ->find();

            if (!$device) {
                return error('设备不存在');
            }

            $deviceName = $device->device_display;
            $device->delete();

            // 记录日志
            UserLog::record($userId, 'update_profile', "删除设备: {$deviceName}");

            return success(null, '设备删除成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取操作日志
     */
    public function getLogs(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $page = $request->param('page', 1);
            $limit = $request->param('limit', 20);
            $action = $request->param('action');

            $query = UserLog::where('user_id', $userId);

            if ($action) {
                $query->where('action', $action);
            }

            $logs = $query->order('created_at', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page,
                ]);

            return success($logs, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取最近登录记录
     */
    public function getRecentLogins(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $limit = $request->param('limit', 10);

            $logs = UserLog::getRecentLogins($userId, $limit);

            return success($logs, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 获取活跃统计
     */
    public function getActiveStats(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $days = $request->param('days', 30);

            $stats = UserLog::getUserActiveStats($userId, $days);

            return success($stats, '获取成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 注销账户
     */
    public function deleteAccount(Request $request)
    {
        try {
            $userId = $request->userId; // 来自中间件
            $password = $request->param('password');

            if (empty($password)) {
                return error('请输入密码确认');
            }

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            // 验证密码
            if (!$user->checkPassword($password)) {
                return error('密码错误');
            }

            // 记录注销日志
            UserLog::record($userId, 'delete_account', '注销账户');

            // 删除用户（级联删除相关数据）
            $user->delete();

            return success(null, '账户注销成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 修改主密码
     */
    public function changeMasterPassword(Request $request)
    {
        try {
            $userId = $request->userId;
            $currentPassword = $request->param('current_password');
            $newPassword = $request->param('new_password');
            $hint = $request->param('hint', '');

            if (empty($currentPassword) || empty($newPassword)) {
                return error('密码不能为空');
            }

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            // 验证当前主密码
            if (!$user->checkMasterPassword($currentPassword)) {
                return error('当前主密码错误');
            }

            // 更新主密码
            $user->master_password_hash = $user->hashMasterPassword($newPassword);
            $user->master_key_hint = $hint;
            $user->master_password_changed_at = date('Y-m-d H:i:s');
            $user->save();

            // 记录日志
            UserLog::record($userId, 'change_master_password', '修改主密码');

            return success(null, '主密码修改成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }


    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request)
    {
        try {
            $userId = $request->userId;
            $file = $request->file('avatar');

            if (!$file) {
                return error('请选择头像文件');
            }

            // 验证文件类型
            if (!in_array($file->getOriginalMime(), ['image/jpeg', 'image/png', 'image/jpg'])) {
                return error('仅支持 JPG、PNG 格式的图片');
            }

            // 验证文件大小（最大2MB）
            if ($file->getSize() > 2 * 1024 * 1024) {
                return error('头像文件不能超过2MB');
            }

            // 生成文件名
            $filename = 'avatar_' . $userId . '_' . time() . '.' . $file->extension();
            $savePath = 'uploads/avatars/' . $filename;

            // 保存文件
            $file->move(root_path() . 'public/' . dirname($savePath), basename($savePath));

            // 更新用户头像
            $user = UserModel::find($userId);
            $user->avatar = '/' . $savePath;
            $user->save();

            // 记录日志
            UserLog::record($userId, 'update_avatar', '更新头像');

            return success(['avatar' => $user->avatar], '头像上传成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 发送邮箱验证
     */
    public function sendEmailVerification(Request $request)
    {
        try {
            $userId = $request->userId;

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            if (empty($user->email)) {
                return error('请先设置邮箱地址');
            }

            if ($user->email_verified) {
                return error('邮箱已经验证过了');
            }

            // 生成验证码
            $code = rand(100000, 999999);
            $expireTime = time() + 300; // 5分钟过期

            // 保存验证码（这里应该存到缓存或数据库）
            cache('email_verify_' . $userId, $code, 300);

            // 发送邮件（这里需要配置邮件服务）
            // 实际项目中需要配置邮件发送服务
            // Mail::send($user->email, '邮箱验证', "您的验证码是：{$code}");

            // 记录日志
            UserLog::record($userId, 'send_email_verify', '发送邮箱验证码');

            return success(null, '验证邮件已发送');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 发送手机验证
     */
    public function sendPhoneVerification(Request $request)
    {
        try {
            $userId = $request->userId;

            $user = UserModel::find($userId);
            if (!$user) {
                return error('用户不存在');
            }

            if (empty($user->phone)) {
                return error('请先设置手机号码');
            }

            if ($user->phone_verified) {
                return error('手机号已经验证过了');
            }

            // 生成验证码
            $code = rand(100000, 999999);

            // 保存验证码（这里应该存到缓存或数据库）
            cache('phone_verify_' . $userId, $code, 300);

            // 发送短信（这里需要配置短信服务）
            // 实际项目中需要配置短信发送服务
            // Sms::send($user->phone, "您的验证码是：{$code}");

            // 记录日志
            UserLog::record($userId, 'send_phone_verify', '发送手机验证码');

            return success(null, '验证短信已发送');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 验证邮箱
     */
    public function verifyEmail(Request $request)
    {
        try {
            $userId = $request->userId;
            $code = $request->param('code');

            if (empty($code)) {
                return error('验证码不能为空');
            }

            // 检查验证码
            $savedCode = cache('email_verify_' . $userId);
            if (!$savedCode || $savedCode != $code) {
                return error('验证码错误或已过期');
            }

            // 更新验证状态
            $user = UserModel::find($userId);
            $user->email_verified = true;
            $user->email_verified_at = date('Y-m-d H:i:s');
            $user->save();

            // 清除验证码
            cache('email_verify_' . $userId, null);

            // 记录日志
            UserLog::record($userId, 'verify_email', '验证邮箱');

            return success(null, '邮箱验证成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 验证手机
     */
    public function verifyPhone(Request $request)
    {
        try {
            $userId = $request->userId;
            $code = $request->param('code');

            if (empty($code)) {
                return error('验证码不能为空');
            }

            // 检查验证码
            $savedCode = cache('phone_verify_' . $userId);
            if (!$savedCode || $savedCode != $code) {
                return error('验证码错误或已过期');
            }

            // 更新验证状态
            $user = UserModel::find($userId);
            $user->phone_verified = true;
            $user->phone_verified_at = date('Y-m-d H:i:s');
            $user->save();

            // 清除验证码
            cache('phone_verify_' . $userId, null);

            // 记录日志
            UserLog::record($userId, 'verify_phone', '验证手机');

            return success(null, '手机验证成功');

        } catch (Exception $e) {
            return error($e->getMessage());
        }
    }
}